import { ref,type Ref } from 'vue'
import { RequestLogin,RequestRegister } from '@/api/index'
import { useAccountStore } from '@/stores/user'
import type{ IAccount} from '@/types/types' 
import { Toast } from 'vant'
import { useRouter} from 'vue-router'

export const useAccount = ()=>{
    // const username = ref<string>('')
    const username:Ref<string> = ref('')
    const password:Ref<string> = ref('')
    const headerimg:Ref<string> = ref('')

    const accountStore = useAccountStore()
    const router = useRouter()

    const bindBack = ()=>history.back()
    /**
     * 登录
     */
    const onSubmit = async()=>{
        const data = await RequestLogin(username.value,password.value)
        const {resultCode,resultInfo,token} = data
        if(resultCode === 1){
            // 保存用户信息,主界面登录按钮换成用户头像
            const account:IAccount = {id:resultInfo.uid,nick:resultInfo.nick,url:resultInfo.headerimg}
            accountStore.saveAccount(account)
            // 保存token
            sessionStorage.setItem('TOKEN',token as string)
            // 登录成功提示，跳转到主界面
            Toast.success('登录成功!')
            router.replace('/')
        }else{
            Toast.fail('账户出错!')
        }
    }
    /**
     * 注册
     */
    const onRegister = async()=>{
        const data = await RequestRegister(username.value,password.value,headerimg.value) 
        const {resultCode} = data
        if(resultCode === 1){
            Toast.success('注册成功!')
            // 跳转到登录界面
            router.replace('/login')
        }
    }



    return {username,password,headerimg, bindBack,onSubmit,onRegister}
}